﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using global::TerhelesEloszto.Common;
using global::TerhelesEloszto.Engine;
using System.Drawing;

namespace Presentation
{
	public partial class Timetable : System.Web.UI.Page
	{
		IEngine engine = global::TerhelesEloszto.Engine.Engine.Instance();
		IAssignmentResult assigment = null;
		String visitorName;

		protected void Page_Load( object sender, EventArgs e )
		{
			visitorName = User.Identity.Name;
			if( !engine.IsAdmin( visitorName ) )
			{
				if( engine.IsTeacher( visitorName ) )
				{
					Response.Redirect( "~/Teacher/TeacherProblem.aspx" );
				}
				else
				{
					Response.Redirect( "~/Problem.aspx" );
				}

			}
			else
			{
				AssignmentStatus status = engine.StatusOfAssignment;
				switch( status )
				{
					case AssignmentStatus.failed:
						StatusLabel.ForeColor = Color.Red;
						StatusLabel.Text = "Sikertelen beosztás.";
						break;

					case AssignmentStatus.none:
						StatusLabel.ForeColor = Color.Orange;
						StatusLabel.Text = "Nem készült beosztás vagy inkonzisztens.";
						break;

					case AssignmentStatus.ok:
						StatusLabel.ForeColor = Color.DarkGreen;
						StatusLabel.Text = "Sikeres beosztás - <a href=\"/Admin/ShowTimeTable.aspx\">megtekintés</a>";
						break;
				}
			}
			if( Request.QueryString["msg"] != null )
			{
				if( Request.QueryString["msg"].Equals( "1" ) ) MessageLabel.Text = "A műveletet sikeresen végrehajtottuk!";
				else if( Request.QueryString["msg"].Equals( "0" ) ) MessageLabel.Text = "Hiba történt a művelet végrehajtása közben";
			}


			if( Request.QueryString["reason"] != null )
			{
				StatusLabel.Text += " - " + Request.QueryString["reason"];
			}

			if( Request.QueryString["first"] != null && Request.QueryString["second"] != null )
			{
				StatusLabel.Text += " - A következő két feladat ütközik:\n " + Request.QueryString["first"] + " és " + Request.QueryString["second"];
			}


		}

		protected void BalanceBtn_Click( object sender, EventArgs e )
		{
			if( engine.LoginUser( visitorName, engine.CreateHash( Passwd.Text ), false ) )
			{
				try
				{
					assigment = engine.CreateAssignment();
					engine.IsTeacherSettingsEnabled = false;

					if( assigment.IsSucceded )
					{
						Response.Redirect( "~/Admin/Timetable.aspx?msg=1" );
					}
					else
					{
						if( assigment.FistConflict == null )
						{
							Response.Redirect( "~/Admin/Timetable.aspx?msg=1&reason=" + assigment.Reason );
						}
						else
						{
							Response.Redirect( "~/Admin/Timetable.aspx?msg=1&first=" + assigment.FistConflict[0].Name.Trim() + "&second=" + assigment.FistConflict[1].Name.Trim() );
						}
					}
				}
				catch( EngineException ex )
				{
					Response.Redirect( "~/Admin/Timetable.aspx?msg=0" );
				}
			}
		}
	}
}